package softswitch.service;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import softswitch.model.Route;
import softswitch.model.RoutePrefix;

@Stateless
public class RoutePrefixDAO {

    @PersistenceContext(unitName = "persistence")
    private EntityManager em;

    public RoutePrefix getById(Integer id) {
        return em.find(RoutePrefix.class, id);
    }

    public RoutePrefix save(RoutePrefix route) {
        em.persist(route);
        return route;
    }

    public RoutePrefix update(RoutePrefix route) {
        return em.merge(route);
    }

    public void delete(Integer id) {
        em.remove(em.find(RoutePrefix.class, id));
    }

    @SuppressWarnings("unchecked")
    public List<RoutePrefix> list(int first, int max) {
        Query query = em.createQuery("SELECT e FROM RoutePrefix e");
        if (max > 0) {
            query.setMaxResults(max);
        }
        if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();
    }
    // ------------------------------------------------------------------------------

    @SuppressWarnings("unchecked")
    public List<RoutePrefix> listByRoute(Route route) {
        List<RoutePrefix> results = null;
        Query query = em.createQuery("SELECT e FROM RoutePrefix e WHERE e.route=:route");
        query.setParameter("route", route);
        try {
            results = query.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    public RoutePrefix getByDestination(String destination) {
        RoutePrefix result = null;
        Query query = em.createNativeQuery("SELECT prefix FROM softswitch.routeprefix WHERE ?1 LIKE CONCAT(prefix,'%') ORDER BY prefix DESC");
        query.setMaxResults(1);
        query.setParameter(1, destination);
        try {
            Integer prefix = (Integer) query.getSingleResult();
            result = getByPrefix(prefix);
        }
        catch (Exception e) {
        	System.out.println();
            //e.printStackTrace();
        }
        return result;
        
    }

    public RoutePrefix getByPrefix(Integer prefix) {
        RoutePrefix result = null;
        Query query = em.createQuery("SELECT e FROM RoutePrefix e WHERE e.prefix = :prefix");
        query.setParameter("prefix", prefix);
        try {
            if (!query.getResultList().isEmpty()) {
                result = (RoutePrefix) query.getResultList().get(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
